import { BaseService } from '@/core/base.service';
import { BaseQueryDto, MessageListDto } from '@/dtos';
import { Injectable } from '@nestjs/common';
import { Message, Prisma } from '@prisma/client';

@Injectable()
export class MessageService extends BaseService {
  async getList(userId: number, { type, params, sort }: MessageListDto) {
    const { current = 1, pageSize = 20, ...where } = params;

    let sql = `
      SELECT #{fields} FROM Message AS t
      WHERE t.isDeleted = false        
        AND t.ownerId = ${userId}        
    `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<Message[]>(
      `${sql.replace(
        '#{fields}',
        `
        t.id, t.title, t.type, t.createdAt
        `,
      )}
      ORDER BY ${
        !!sort && Object.keys(sort).length > 0
          ? Object.entries(sort)
              .map(([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`)
              .join(',')
          : 't.createdAt DESC'
      }
      LIMIT ${pageSize} 
      OFFSET ${(current - 1) * pageSize}
      `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list,
    };
  }

  async query({ params, sort }: BaseQueryDto<Prisma.MessageWhereUniqueInput>) {
    const { current = 1, pageSize = 20, keyword, ...where } = params;

    let sql = `
      SELECT #{fields} FROM Message AS t
      WHERE t.isDeleted = false
        ${!!where.title ? `AND t.title LIKE '%${where.title}%'` : ''}
    `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<Message[]>(
      `${sql.replace(
        '#{fields}',
        't.id, t.title, t.type, t.content, t.createdAt, t.sort, t.isEnabled',
      )}
      ORDER BY ${
        !!sort && Object.keys(sort).length > 0
          ? Object.entries(sort)
              .map(([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`)
              .join(',')
          : 't.createdAt DESC'
      }
      LIMIT ${pageSize} 
      OFFSET ${(current - 1) * pageSize}
      `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list,
    };
  }

  async findOne(
    where: Prisma.MessageWhereUniqueInput,
    select?: Prisma.MessageSelect,
  ): Promise<Message | null> {
    return this.prisma.message.findUnique({
      where,
      select,
    });
  }

  async create(data: Prisma.MessageCreateInput): Promise<Message> {
    return await this.prisma.message.create({
      data,
    });
  }

  async update(params: {
    where: Prisma.MessageWhereUniqueInput;
    data: Prisma.MessageUpdateInput;
  }): Promise<Message> {
    const { where, data } = params;
    return this.prisma.message.update({
      where,
      data,
    });
  }

  async remove(where: Prisma.MessageWhereUniqueInput): Promise<Message> {
    return this.prisma.message.update({
      where,
      data: {
        isDeleted: true,
      },
    });
  }
}
